package cn.yshujia.repository;

import cn.yshujia.domain.entity.Classify;
import cn.yshujia.mapper.ClassifyMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author YShuJia
 * @create 2024/11/29
 * @description ClassifyRepository
 */
@Repository
public class ClassifyRepository {
	
	@Resource
	RedisTemplate<String, Classify> redis;
	
	@Resource
	ClassifyMapper mapper;
	
	public static final String VO = "classify:";
	
	public static final String LIST_TYPE = "classify:type:";
	
	public static final String LIST_ALL = "classify:all";
	
	public static final Duration DURATION = Duration.ofDays(3L);
	
	public Classify selectById(Long id) {
		Classify classify = redis.opsForValue().get(VO + id);
		if (null != classify) {
			return classify;
		}
		classify = mapper.selectById(id);
		if (null != classify) {
			redis.opsForValue().set(VO + id, classify, DURATION);
		}
		return classify;
	}
	
	public List<Classify> selectListByType(Integer type) {
		String key = type == -1 ? LIST_ALL : LIST_TYPE + type;
		// 从缓存中获取
		List<Classify> list = redis.opsForList().range(key, 0L, -1L);
		if (!ObjectUtils.isEmpty(list)) {
			return list;
		}
		LambdaQueryWrapper<Classify> wrapper = new LambdaQueryWrapper<>();
		if (-1 != type) {
			wrapper.eq(Classify::getType, type);
		}
		list = mapper.selectList(wrapper);
		if (ObjectUtils.isEmpty(list)) {
			return new ArrayList<>();
		}
		set(list, key);
		return list;
	}
	
	@Async ("Task")
	public void set(List<Classify> value, String key) {
		redis.opsForList().rightPushAll(key, value);
		redis.opsForList().getOperations().expire(key, DURATION);
	}
	
	@Async ("Task")
	public void del() {
		Set<String> keys = redis.keys(VO + "*");
		redis.delete(keys);
	}
}
